package cn.turboinfo.fuyang.api.provider.admin.component.security.impl;

import cn.turboinfo.fuyang.api.domain.util.SecurityUtils;
import cn.turboinfo.fuyang.api.provider.admin.component.security.SecurityEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * author: sunshow.
 */
@Slf4j
public class RSASecurityEncoder implements SecurityEncoder {

    private final String base64RSAPublicKey;

    private final byte[] privateKey;

    public RSASecurityEncoder(String base64RSAPublicKey, String base64RSAPrivateKey) {
        this.base64RSAPublicKey = base64RSAPublicKey;

        if (StringUtils.isNotEmpty(base64RSAPrivateKey)) {
            this.privateKey = SecurityUtils.decodeBase64(base64RSAPrivateKey);
        } else {
            this.privateKey = null;
        }
    }

    @Override
    public String getPublicKey() {
        return base64RSAPublicKey;
    }

    public String decrypt(String encrypted) {
        if (privateKey != null) {
            return new String(SecurityUtils.decryptRSA(SecurityUtils.decodeHex(encrypted), privateKey), StandardCharsets.UTF_8);
        }
        throw new RuntimeException("未正确配置RSA密钥");
    }

}
